package com.agileai.miscdp.hotweb.ui.actions.treemanage;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.progress.IProgressService;

import com.agileai.miscdp.hotweb.domain.PageFormField;
import com.agileai.miscdp.hotweb.domain.treemanage.TreeManageFuncModel;
import com.agileai.miscdp.hotweb.generator.treemanage.TMMHandlerCfgGenerator;
import com.agileai.miscdp.hotweb.generator.treemanage.TMMHandlerGenerator;
import com.agileai.miscdp.hotweb.generator.treemanage.TMMJspPagGenerator;
import com.agileai.miscdp.hotweb.generator.treemanage.TMMServiceCfgGenerator;
import com.agileai.miscdp.hotweb.generator.treemanage.TMMServiceClassGenerator;
import com.agileai.miscdp.hotweb.generator.treemanage.TMMServiceInterfaceGenerator;
import com.agileai.miscdp.hotweb.generator.treemanage.TMMSqlMapCfgGenerator;
import com.agileai.miscdp.hotweb.generator.treemanage.TMMSqlMapGenerator;
import com.agileai.miscdp.hotweb.ui.actions.BaseGenCodesAction;
import com.agileai.miscdp.hotweb.ui.dialogs.CodeGenConfigDialog;
import com.agileai.miscdp.hotweb.ui.editors.treemanage.TreeManageModelEditor;
import com.agileai.miscdp.hotweb.ui.editors.treemanage.TreeManageModelEditorContributor;
import com.agileai.miscdp.util.DialogUtil;
import com.agileai.miscdp.util.MiscdpUtil;
import com.agileai.domain.KeyNamePair;
import com.agileai.util.FileUtil;
import com.agileai.util.StringUtil;
/**
 * 代码生成动作
 */
public class TMMGenCodesAction extends BaseGenCodesAction{
	private static final String GenOptionSection = "TreeManageModelEditor.GeneratorOption";
	
	public TMMGenCodesAction() {
	}
	public void setContributor(TreeManageModelEditorContributor contributor) {
		this.contributor = contributor;
	}
	public void run() {
		TreeManageModelEditor modelEditor = (TreeManageModelEditor)this.getModelEditor();
    	
		String idFieldName = modelEditor.getBasicConfigPage().getIdFieldText().getText();
    	if (StringUtil.isNullOrEmpty(idFieldName)){
    		String idFieldCheckNullMsg = MiscdpUtil.getIniReader().getValue("TreeManageModelEditor","IdFieldCheckNullMsg");
    		DialogUtil.showInfoMessage(idFieldCheckNullMsg);
    		return;
    	}
    	
		String nameFieldName = modelEditor.getBasicConfigPage().getNameFieldText().getText();
    	if (StringUtil.isNullOrEmpty(nameFieldName)){
    		String nameFieldCheckNullMsg = MiscdpUtil.getIniReader().getValue("TreeManageModelEditor","NameFieldCheckNullMsg");
    		DialogUtil.showInfoMessage(nameFieldCheckNullMsg);
    		return;
    	}
    	
		String pidFieldName = modelEditor.getBasicConfigPage().getPidFieldText().getText();
    	if (StringUtil.isNullOrEmpty(pidFieldName)){
    		String pIdFieldFieldCheckNullMsg = MiscdpUtil.getIniReader().getValue("TreeManageModelEditor","PIdFieldCheckNullMsg");
    		DialogUtil.showInfoMessage(pIdFieldFieldCheckNullMsg);
    		return;
    	}
    	
		String sortFieldName = modelEditor.getBasicConfigPage().getSortFieldText().getText();
    	if (StringUtil.isNullOrEmpty(sortFieldName)){
    		String sortFieldCheckNullMsg = MiscdpUtil.getIniReader().getValue("TreeManageModelEditor","SortFieldCheckNullMsg");
    		DialogUtil.showInfoMessage(sortFieldCheckNullMsg);
    		return;
    	}
    	funcModel = modelEditor.buildFuncModel();
    	String sortField = ((TreeManageFuncModel)funcModel).getSortField();
    	List<PageFormField> pageFormFields = ((TreeManageFuncModel)funcModel).getPageFormFields();
    	for (int i=0;i < pageFormFields.size();i++){
    		PageFormField pageFormField = pageFormFields.get(i);
    		String tageType = pageFormField.getTagType();
    		String code = pageFormField.getCode();
    		if (code.equals(sortField) && !"hidden".equals(tageType)){
    			String sortFieldMustHiddenMsg = MiscdpUtil.getIniReader().getValue("TreeManageModelEditor","SortFieldMustHiddenMsg");
        		DialogUtil.showInfoMessage(sortFieldMustHiddenMsg);
    			return;
    		}
    	}
		
		Shell shell = modelEditor.getSite().getShell();
    	if (modelEditor.isDirty()){
    		String confirmTitle = MiscdpUtil.getIniReader().getValue("DialogInfomation","ConfirmTitle");
    		String confirmMsg = MiscdpUtil.getIniReader().getValue("DialogInfomation","IsSaveFirst");
    		boolean saveFirst = MessageDialog.openConfirm(shell, confirmTitle, confirmMsg);
    		if (saveFirst){
    			modelEditor.doSave(new NullProgressMonitor());
    		}else{
    			return;
    		}
    	}
    	
		CodeGenConfigDialog configDialog = new CodeGenConfigDialog(shell);
		List<KeyNamePair> inputGenList = new ArrayList<KeyNamePair>();
		inputGenList = MiscdpUtil.getIniReader().getList(GenOptionSection);
		configDialog.setInputGenList(inputGenList);
		configDialog.open();
		if (configDialog.getReturnCode() != Dialog.OK){
			return;
		}
		genertorMap = configDialog.getSelectedKeyNamePairs();
    	
		IProgressService progressService = PlatformUI.getWorkbench().getProgressService();
		try {
	    	String projectName = funcModel.getProjectName();
	    	IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
			progressService.runInUI(progressService,this,project);
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	public void run(IProgressMonitor monitor) throws InvocationTargetException,
			InterruptedException {
		monitor.beginTask("init model values:", 1000);
		monitor.subTask("set model values....");
		monitor.worked(50);
		
		File xmlFile = getXmlFile();
    	String projectName = funcModel.getProjectName();
    	IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
    	String srcDir = project.getLocation().toString()+"/src";
    	String tableName = ((TreeManageFuncModel)funcModel).getTableName();
//    	this.funcModel = funcModel.buildFuncModel(xmlFile);
    	
    	if (genertorMap.containsKey(GEN_OPTION_JSPPAGE)){
    		monitor.subTask("generating jsp files....");
    		monitor.worked(200);
    		TMMJspPagGenerator sMJspPagGenerator = new TMMJspPagGenerator();
    		sMJspPagGenerator.setXmlFile(xmlFile);
    		String jspName = ((TreeManageFuncModel)funcModel).getJspName();
        	String listJspName = project.getLocation().toString()+"/WebRoot/jsp/"+jspName;
    		sMJspPagGenerator.setJspFile(listJspName);
    		sMJspPagGenerator.setFuncModel(((TreeManageFuncModel)funcModel));
    		String parentSelectJspFile = listJspName.substring(0,listJspName.indexOf(".jsp")-10)+"ParentSelect"+".jsp";
    		sMJspPagGenerator.setParentSelectJspFile(parentSelectJspFile);
    		sMJspPagGenerator.generate();
    	}

    	if (genertorMap.containsKey(GEN_OPTION_SQLMAP_DEFINE)){
    		monitor.subTask("generating SqlMap files....");
    		monitor.worked(300);
    		TMMSqlMapGenerator sMSqlMapGenerator = new TMMSqlMapGenerator();
    		sMSqlMapGenerator.setFuncModel((TreeManageFuncModel)funcModel);
    		sMSqlMapGenerator.setTableName(tableName);
        	String abstSqlMapPath = project.getLocation().toString()+"/src/sqlmap";
        	File tempFile = new File(abstSqlMapPath);
        	if (!tempFile.exists()){
        		tempFile.mkdirs();
        	}
        	String sqlMapFileName = MiscdpUtil.getValidName(tableName); 
        	String sqlMapFile = abstSqlMapPath + "/" + sqlMapFileName+".xml";
        	sMSqlMapGenerator.setSqlMapFile(sqlMapFile);
    		sMSqlMapGenerator.generate();
    	}
    	
    	if (genertorMap.containsKey(GEN_OPTION_SQLMAP_INDEX)){
    		monitor.subTask("generating SqlMap config files....");
    		monitor.worked(400);
    		TMMSqlMapCfgGenerator sMSqlMapCfgGenerator = new TMMSqlMapCfgGenerator();
    		String abstSqlMapCfgPath = project.getLocation().toString()+"/src/SqlMapConfig.xml";
    		sMSqlMapCfgGenerator.setTableName(tableName);
    		sMSqlMapCfgGenerator.setConfigFile(abstSqlMapCfgPath);
    		sMSqlMapCfgGenerator.generate();
    	}
		
    	if (genertorMap.containsKey(GEN_OPTION_SERVICE_CONFIG)){
    		monitor.subTask("generating Service config files....");
    		monitor.worked(500);
    		TMMServiceCfgGenerator sMServiceCfgGenerator = new TMMServiceCfgGenerator();
    		String abstServiceCfgPath = project.getLocation().toString()+"/src/ServiceContext.xml";
    		sMServiceCfgGenerator.setConfigFile(abstServiceCfgPath);
    		sMServiceCfgGenerator.setFuncModel((TreeManageFuncModel)funcModel);
    		sMServiceCfgGenerator.generate();
    	}

    	if (genertorMap.containsKey(GEN_OPTION_HANDLER_CONFIG)){
    		monitor.subTask("generating Handler config files....");
    		monitor.worked(600);
    		TMMHandlerCfgGenerator sMHandlerCfgGenerator = new TMMHandlerCfgGenerator();
    		String abstHandlerCfgPath = project.getLocation().toString()+"/src/HandlerContext.xml";
    		sMHandlerCfgGenerator.setConfigFile(abstHandlerCfgPath);
    		sMHandlerCfgGenerator.setFuncModel((TreeManageFuncModel)funcModel);
    		sMHandlerCfgGenerator.generate();
    	}
		
    	if (genertorMap.containsKey(GEN_OPTION_HANDLER_CLASS)){
    		monitor.subTask("generating Handler java files....");
    		monitor.worked(700);
    		TMMHandlerGenerator sMHandlerGenerator = new TMMHandlerGenerator();
    		sMHandlerGenerator.setSrcPath(srcDir);
    		TreeManageFuncModel treemanageFuncModel = (TreeManageFuncModel)funcModel;
    		String listHandlerClassName = treemanageFuncModel.getHandlerClass();
    		sMHandlerGenerator.setHandlerClassName(listHandlerClassName);
    		sMHandlerGenerator.setParentSelectHandlerClassName(listHandlerClassName.substring(0,listHandlerClassName.length()-17)+"ParentSelectHandler");
    		sMHandlerGenerator.setXmlFile(xmlFile);
    		sMHandlerGenerator.generate();
    	}

    	if (genertorMap.containsKey(GEN_OPTION_SERVICE_IMPL)){
    		monitor.subTask("generating Service Impl java files....");
    		monitor.worked(800);
    		TMMServiceClassGenerator sMServiceClassGenerator = new TMMServiceClassGenerator();
    		String implClassName = funcModel.getImplClassName();
    		File implJavaFile = FileUtil.createJavaFile(srcDir, implClassName);
    		String implJavaFilePath = implJavaFile.getAbsolutePath();
    		sMServiceClassGenerator.setJavaFile(implJavaFilePath);
    		sMServiceClassGenerator.setXmlFile(xmlFile);
    		sMServiceClassGenerator.generate();
			
    		try {
				MiscdpUtil.getJavaFormater().format(implJavaFilePath, sMServiceClassGenerator.getCharencoding());
			} catch (IOException e1) {
				e1.printStackTrace();
				throw new InvocationTargetException(e1);
			}
    	}

    	if (genertorMap.containsKey(GEN_OPTION_SERVICE_INTERFACE)){
    		monitor.subTask("generating Service Interface java files....");
    		monitor.worked(900);
    		TMMServiceInterfaceGenerator sMServiceInterfaceGenerator = new TMMServiceInterfaceGenerator();
    		String interfaceClassName = funcModel.getInterfaceName();
    		File interfaceJavaFile = FileUtil.createJavaFile(srcDir, interfaceClassName);
    		String interfaceJavaFilePath = interfaceJavaFile.getAbsolutePath();
    		sMServiceInterfaceGenerator.setJavaFile(interfaceJavaFilePath);
    		sMServiceInterfaceGenerator.setXmlFile(xmlFile);
    		sMServiceInterfaceGenerator.generate();
    		
			try {
				MiscdpUtil.getJavaFormater().format(interfaceJavaFilePath, sMServiceInterfaceGenerator.getCharencoding());
			} catch (IOException e1) {
				e1.printStackTrace();
				throw new InvocationTargetException(e1);
			}
    	}
			
		try {
			project.refreshLocal(IResource.DEPTH_INFINITE, null);
		} catch (CoreException e) {
			e.printStackTrace();
		}
	}
}
